<!--
 * @Author yuec621@outLook.com
 * @Description: 开关量模拟量对比图表组件
 * @Date: 2024-11-04 13:34:02
 * @LastEditTime: 2024-11-14 13:58:35
 * @LastEditors: Please set LastEditors
 * @Reference: 
-->
<template>
    <div>
        <div id="comChart" style="width: 100%;height: 500px;">
        </div>
        <symbolCard v-if="state.symShow" :symbolObj="state.symbolObj" :style="{
        position: 'absolute',
        left: state.xydata.x + 'px',
        top: state.xydata.y + 'px',
        zIndex: 1,
      }" @mouseleave="mouseleavesymbol"></symbolCard>
        <youBoxCom v-if="state.youBoxShow" :style="{
        position: 'absolute',
        left: state.youXY.x * 2 + 'px',
        bottom: toolType == '5' ? 60 + '%' : state.youXY.y * 3 + '%',
        zIndex: 1,
      }" :youBoxList="state.youBoxList">
        </youBoxCom>
    </div>
</template>
<script setup>
    import symbolCard from "./symbolCard.vue";
    import youBoxCom from "./youBoxCom.vue";
    import {
        computed,
        nextTick,
        reactive,
        watchEffect
    } from 'vue';
    import * as echarts from 'echarts'
    import dayjs from 'dayjs'
    import printJS from "print-js";
    import _ from "lodash";
    import useUserStore from "@/store/modules/user";
    import imgIcon from "@/assets/images/youbiao.png";
    const {
        proxy
    } = getCurrentInstance();
    const userStore = useUserStore();
    const emits = defineEmits(["toolChange"]);
    const props = defineProps({
        chartList: {
            type: Object,
            default: () => {
                return {}
            }
        },
        attrObj: {
            type: Object,
            default: () => {
                return undefined
            }
        },
        statusList: {
            type: Object,
            default: () => {
                return {}
            }
        },
        symbolShow: {
            type: String,
            default: () => {
                return 'none'
            }
        },
        splitNumber: {
            type: Number,
            default: () => {
                return 20
            }
        },
        toolType: {
            type: String,
            default: () => {
                return ''
            }
        },
        nameListstatus: {
            type: Array,
            default: () => {
                return []
            }
        },
        maxMinScale:{
            type: Object,
            default: () => {
                return {
                    upperRestriction: undefined,
                    lowerRestriction: undefined
                }
            }
        }

    })
    let comChart
    const state = reactive({
        chartShow: true,
        xydata: {
            x: 0,
            y: 0,
        },
        symShow: false,
        symbolObj: {},
        symbolShow: false,
        splitNumber: 10,
        youXY: {
            x: 0,
            y: 0,
        },
        youBoxShow: false,
        youBoxList: [],
        maxMinScale:{}
    })

    function setC1(chartList, statusList) {
        let data = []
        var categories = [];
        let xdata = []
        let serArr = []
        let xdataAlarm = []
        if (JSON.stringify(statusList) != "{}") {
            xdata = statusList.allTimes.map(item => {
                return dayjs(item).format('MM-DD HH:mm');
            })
            if (statusList.switchPointLines != null) {
                statusList.switchPointLines.forEach((item) => {
                    categories.push(item.pointId)
                    item.switchStateLines.forEach(itemsub => {
                        itemsub.pointId = item.pointId
                        itemsub.lengedList = item.lengedList
                        if (item.lengedList.length > 0) {
                            if (item.lengedList.length == 3) {
                                if (itemsub.stateValue == 0) {
                                    itemsub.name = item.lengedList[0].connotation
                                } else if (itemsub.stateValue == 1) {
                                    itemsub.name = item.lengedList[1].connotation
                                } else if (itemsub.stateValue == 2) {
                                    itemsub.name = item.lengedList[2].connotation
                                } else if (itemsub.stateValue == null) {
                                    itemsub.name = '网络故障/分站故障'
                                }
                            } else if (item.lengedList.length == 2) {
                                if (itemsub.stateValue == 0) {
                                    itemsub.name = item.lengedList[0].connotation
                                } else if (itemsub.stateValue == 1) {
                                    itemsub.name = item.lengedList[1].connotation
                                } else if (itemsub.stateValue == null) {
                                    itemsub.name = '网络故障/分站故障'
                                }
                            }
                        }
                        data.push(itemsub)
                    })
                })
            }
        }
        if (JSON.stringify(chartList) != "{}") {
            xdataAlarm = chartList.allTimes.map(item => {
                return dayjs(item).format('YYYY-MM-DD HH:mm:ss')
            })
            chartList.hisSimulateLines.forEach(item => {
                serArr.push({
                    name: item.pointId + item.place,
                    type: "line",
                    smooth: item.attrObj && item.attrObj
                        .maxchartType ? item.attrObj
                        .maxchartType : false,
                    symbolSize: 8,
                    xAxisIndex: 0,
                    yAxisIndex: 1,
                    symbol: props.symbolShow || (item.attrObj && item.attrObj.maxdotSwitch) || (props
                            .attrObj && props.attrObj.chartDot) ?
                        'circle' : 'none', //"circle",
                    itemStyle: {
                        color: item.color != null ? item.color : item.attrObj && item.attrObj
                            .maxlineColor ? item.attrObj.maxlineColor : 'rgba(68, 170, 255, 1)'
                    },
                    lineStyle: {
                        width: item.attrObj && item.attrObj.maxlineWidth ?
                            item.attrObj.maxlineWidth : 2,
                        opacity: item.maxShow ? item.opacitymax : item.opacity,
                        color: item.color != null ? item.color : item.attrObj && item.attrObj
                            .maxlineColor ? item.attrObj.maxlineColor : 'rgba(68, 170, 255, 1)',
                        type: item.attrObj && item.attrObj
                            .maxlineType ? item.attrObj
                            .maxlineType : false,
                    },
                    data: item.hisSimulatePoints.map(itemsub => {
                        return [
                            dayjs(itemsub.dataTime).format("YYYY-MM-DD HH:mm:ss"),
                            itemsub.maxValue,
                        ]
                    })
                }, {
                    name: item.pointId + item.place,
                    type: "line",
                    smooth: item.attrObj && item.attrObj
                        .minchartType ? item.attrObj
                        .minchartType : false,
                    symbolSize: 8,
                    xAxisIndex: 0,
                    yAxisIndex: 1,
                    symbol: props.symbolShow || (item.attrObj && item.attrObj.mindotSwitch) || (props
                            .attrObj && props.attrObj.chartDot) ?
                        'circle' : 'none', //"circle",
                    itemStyle: {
                        color: item.color != null ? item.color : item.attrObj && item.attrObj
                            .minlineColor ? item.attrObj.minlineColor : 'rgba(102, 136, 255, 1)'
                    },
                    lineStyle: {
                        width: item.attrObj && item.attrObj.minlineWidth ?
                            item.attrObj.minlineWidth : 2,
                        opacity: item.maxShow ? item.opacitymin : item.opacity,
                        color: item.color != null ? item.color : item.attrObj && item.attrObj
                            .minlineColor ? item.attrObj.minlineColor : 'rgba(102, 136, 255, 1)',
                        type: item.attrObj && item.attrObj
                            .minlineType ? item.attrObj
                            .minlineType : false,
                    },
                    data: item.hisSimulatePoints.map(itemsub => {
                        return [
                            dayjs(itemsub.dataTime).format("YYYY-MM-DD HH:mm:ss"),
                            itemsub.minValue,
                        ]
                    })
                }, {
                    name: item.pointId + item.place,
                    type: "line",
                    smooth: item.attrObj && item.attrObj
                        .avgchartType ? item.attrObj
                        .avgchartType : false,
                    xAxisIndex: 0,
                    yAxisIndex: 1,
                    symbolSize: 8,
                    symbol: props.symbolShow || (item.attrObj && item.attrObj.avgdotSwitch) || (props
                            .attrObj && props.attrObj.chartDot) ?
                        'circle' : 'none', //"circle",
                    itemStyle: {
                        color: item.color != null ? item.color : item.attrObj && item.attrObj
                            .avglineColor ? item.attrObj.avglineColor : 'rgba(221, 119, 238, 1)'
                    },
                    lineStyle: {
                        width: item.attrObj && item.attrObj.avglineWidth ?
                            item.attrObj.avglineWidth : 2,
                        opacity: item.maxShow ? item.opacityavg : item.opacity,
                        color: item.color != null ? item.color : item.attrObj && item.attrObj
                            .avglineColor ? item.attrObj.avglineColor : 'rgba(221, 119, 238, 1)',
                        type: item.attrObj && item.attrObj
                            .avglineType ? item.attrObj
                            .avglineType : false,
                    },
                    data: item.hisSimulatePoints.map(itemsub => {
                        return [
                            dayjs(itemsub.dataTime).format("YYYY-MM-DD HH:mm:ss"),
                            itemsub.avgValue,
                        ]
                    })
                })
            })
        }
        let this_ = {};
        let statusObj = {}
        if (props.nameListstatus) {
            props.nameListstatus.forEach(item => {
                statusObj[item.id] = item.displayValue
            })
        }
        this_.colmap = statusObj
        if (data.length > 0) {
            this_.startTime = dayjs(data[0].stateStartTime).valueOf()
        }
        this_.dataE = data.map(item => {
            const obj = item.lengedList.reduce((acc, {
                connotation,
                displayValue
            }) => {
                acc[connotation] = displayValue;
                acc['网络故障/分站故障']='#eee'
                return acc;
            }, {});
            return {
                name: item.name,
                lengedList: obj,
                value: [item.pointId, dayjs(item.stateStartTime).valueOf(), dayjs(item.stateEndTime)
                    .valueOf()
                ]
            }
        })
        for (var i = 0; i < this_.dataE.length; i++) {
            this_.dataE[i].itemStyle = {
                normal: {
                    color: this_.dataE[i].lengedList[this_.dataE[i].name]
                },
            };
        }
        let renderItem = function (params, api) {
            var categoryIndex = api.value(0);
            var start = api.coord([api.value(1), categoryIndex]);
            var end = api.coord([api.value(2), categoryIndex]);
            var height = api.size([0, 1])[1] * 0.3;
            var rectShape = echarts.graphic.clipRectByRect({
                x: start[0],
                y: start[1] - height / 2,
                width: end[0] - start[0],
                height: height,
            }, {
                x: params.coordSys.x,
                y: params.coordSys.y,
                width: params.coordSys.width,
                height: params.coordSys.height,
            });
            return (
                rectShape && {
                    type: "rect",
                    transition: ["shape"],
                    shape: rectShape,
                    style: api.style(),
                }
            );
        };
        let option = {
            tooltip: {
                formatter: function (param) {
                    if (param.length > 0) {
                        let arrNew = [];
                        let arrName = _.uniq(
                            param.map((item) => {
                                return {
                                    name: item.seriesName,
                                    idx: item.dataIndex,
                                };
                            })
                        );
                        if (JSON.stringify(chartList) != "{}") {
                            chartList.hisSimulateLines.forEach((item) => {
                                arrName.forEach((itemsub) => {
                                    if (itemsub.name == item.pointId + item.place) {
                                        arrNew.push({
                                            place: item.place,
                                            unit: item.unit,
                                            ...item.hisSimulatePoints[itemsub.idx],
                                        });
                                    }
                                });
                            });
                        }
                        let youBoxArr = _.unionBy(arrNew, "pointId");
                        state.youBoxList = [{
                            place: "类型",
                            maxValue: "最大值",
                            minValue: "最小值",
                            avgValue: "平均值",
                            unit: undefined,
                        }, ].concat(youBoxArr);
                        state.youBoxShow = true;
                        state.youXY.x = param[0].dataIndex;
                    }
                },
            },
            title: {
                text: props.attrObj && props.attrObj.chartTitle,
                left: "center",
                top: 10,
            },
            toolbox: {
                show: true,
                y: "-30",
            },
            brush: {
                xAxisIndex: "all",
                brushLink: "all",
                seriesIndex: "all",
                // 选框中的视觉元素样式
                inBrush: {
                    symbol: "circle", // 图元图形 可以是'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin'
                    symbolSize: 32, // 图元大小
                    color: "red", // 图元颜色
                    colorAlpha: 0.5, // 图元透明度
                    opacity: 0.8, // 图元以及其附属物的透明度
                },
                // 未选中的视觉元素样式
                outOfBrush: {
                    symbol: "circle", // 图元图形 可以是'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin'
                    symbolSize: 32, // 图元大小
                    color: "red", // 图元颜色
                    colorAlpha: 0.5, // 图元透明度
                    opacity: 0.8, // 图元以及其附属物的透明度
                },
            },
            grid: {
                top: 60,
                left: statusList.switchPointLines != null && statusList.switchPointLines.length > 0 ? 60 : 10,
                right: 40,
                bottom: 30
            },
            dataZoom: [{
                    type: "inside",
                    filterMode: "weakFilter",
                    showDataShadow: false,
                    top: 400,
                    height: 10,
                    borderColor: "transparent",
                    backgroundColor: "#e2e2e2",
                    handleIcon: "M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z", // jshint ignore:line
                    handleSize: 20,
                    start: 0,
                    end: 60,
                    handleStyle: {
                        shadowBlur: 6,
                        shadowOffsetX: 1,
                        shadowOffsetY: 2,
                        shadowColor: "#aaa",
                    },
                    labelFormatter: "",
                },
                {
                    type: "inside",
                    filterMode: "weakFilter",
                },
            ],
            xAxis: [{
                    show: true,
                    data: xdataAlarm,
                    axisPointer: {
                        show: props.toolType == "5" || props.toolType == "6" ? true : false,
                        lineStyle: {
                            color: "#004E52",
                            opacity: 0.5,
                            width: 2,
                            type: "solid",
                        },
                        snap: false, //true必须在点上，false任意位置
                        handle: {
                            show: true,
                            size: 20,
                            margin: 60,
                            color: "#DC143C",
                            throttle: 100,
                            margin: -450,
                            icon: `image://${imgIcon}`,
                        },
                        triggerTooltip: true,
                        triggerEmphasis: true,
                    },
                    axisTick: {
                        show: false
                    },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(91, 109, 128, 0.8)'
                        }
                    },
                    axisLabel: {
                        formatter: function (val) {
                            return dayjs(val).format('MM-DD HH:mm');
                        },
                        color: 'rgba(62, 70, 79, 1)'
                    },
                    splitLine: {
                        show: props.attrObj && props.attrObj.chartGrid,
                        lineStyle: {
                            color: 'rgba(91, 109, 128, 0.16)',
                            type: 'dashed'
                        }
                    }
                }, {
                    show: false,
                    // min: 1620576000000,
                    type: 'time',
                    scale: true,
                    axisLabel: {
                        formatter: function (val) {
                            return dayjs(val).format('MM-DD HH:mm');
                        },
                        color: 'rgba(62, 70, 79, 1)'
                    },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(91, 109, 128, 0.8)'
                        }
                    },
                    axisTick: {
                        show: false
                    },
                    splitLine: {
                        show: props.attrObj && props.attrObj.chartGrid,
                        lineStyle: {
                            color: 'rgba(91, 109, 128, 0.16)',
                            type: 'dashed'
                        }
                    }
                },

            ],
            yAxis: [{
                    data: categories,
                    axisTick: {
                        show: false
                    },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(91, 109, 128, 0.8)'
                        }
                    },
                    axisLabel: {
                        formatter: function (params) {
                            return params;
                        },
                        textStyle: {
                            color: "#000",
                            fontWeight: "600",
                        },
                    },
                    splitLine: {
                        show: props.attrObj && props.attrObj.chartGrid,
                        lineStyle: {
                            color: 'rgba(91, 109, 128, 0.16)',
                            type: 'dashed'
                        }
                    }
                },
                {
                    name: props.attrObj && props.attrObj.chartY,
                    min:state.maxMinScale.lowerRestriction,
                    max:state.maxMinScale.upperRestriction,
                    type: "value",
                    // interval: 30,
                    splitNumber: state.splitNumber, //纵向放大
                    axisTick: {
                        show: false
                    },
                    splitLine: {
                        show: false,
                        lineStyle: {
                            color: 'rgba(91, 109, 128, 0.16)',
                            type: 'dashed'
                        }
                    },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(91, 109, 128, 0.8)'
                        }
                    },
                    axisLabel: {
                        formatter: function (params) {
                            return params;
                        },
                        textStyle: {
                            color: "#000",
                            fontWeight: "600",
                        },
                    },
                    axisPointer: {
                        show: props.toolType == "6" ? true : false,
                        value: 200,
                        lineStyle: {
                            color: "#004E52",
                            opacity: 0.5,
                            width: 2,
                            type: "dashed",
                        },
                        label: {
                            formatter: function (param) {
                                state.youXY.y = props.toolType == "5" ? 35 : param.value + 8;
                                return;
                            },
                        },
                        snap: false,
                        value: 100,
                        handle: {
                            show: true,
                            size: 20,
                            margin: 60,
                            color: "#DC143C",
                            throttle: 100,
                        },
                        triggerTooltip: false,
                    },
                },
            ],
            series: [{
                    type: "custom",
                    renderItem: renderItem,
                    stack: "总量",
                    xAxisIndex: 1,
                    yAxisIndex: 0,
                    itemStyle: {
                        normal: {},
                    },
                    encode: {
                        x: [1, 2],
                        y: 0,
                    },
                    data: this_.dataE,
                },
                ...serArr
            ],
        };
        comChart.setOption(option, true)
        comChart.on("mouseover", function (param) {
            if(param.componentSubType =='line'){
                //拐点弹框位置及弹框数据
                if (param.event.offsetX > 1400) {
                    param.event.offsetX = param.event.offsetX - 400;
                }
                state.xydata.x = param.event.offsetX;
                state.xydata.y = param.event.offsetY;
                state.symShow = true;
                if (JSON.stringify(chartList) != "{}") {
                    chartList.hisSimulateLines.forEach((item) => {
                        if (param.seriesName == item.pointId + item.place) {
                            let dataObj = item.hisSimulatePoints[param.dataIndex];
                            state.symbolObj = {
                                pointId: item.pointId,
                                pointName: item.sensorName,
                                place: item.place,
                                timeRange: [dataObj.intervalStart, dataObj.intervalEnd],
                                list: [{
                                        label: "最大值",
                                        value: dataObj.maxValue,
                                        unit: item.unit,
                                        state: item.color == null ? "blue" : item.color,
                                    },
                                    {
                                        label: "最大值时刻",
                                        unit: dayjs(dataObj.maxValueTime).format(
                                            "YYYY-MM-DD HH:mm:ss"),
                                    },
                                    {
                                        label: "最小值",
                                        value: dataObj.minValue,
                                        unit: item.unit,
                                        state: "blue",
                                    },
                                    {
                                        label: "平均值",
                                        value: dataObj.avgValue,
                                        unit: item.unit,
                                        state: "blue",
                                    },
                                    {
                                        label: "报警",
                                        value: dataObj.alarmNum,
                                        unit: item.unit,
                                        state: "blue",
                                    },
                                    {
                                        label: "累计时长",
                                        unit: dataObj.alarmDuration,
                                        state: "",
                                    },
                                    {
                                        label: "断电",
                                        value: dataObj.cutNum,
                                        unit: item.unit,
                                        state: "blue",
                                    },
                                    {
                                        label: "累计时长",
                                        unit: dataObj.cutDuration,
                                        state: "",
                                    },
                                    {
                                        label: "馈电异常",
                                        value: dataObj.feedNum,
                                        unit: item.unit,
                                        state: "blue",
                                    },
                                    {
                                        label: "累计时长",
                                        unit: dataObj.feedDuration,
                                        state: "",
                                    },
                                ],
                            };
                        }
                    });
                }
            }
        });
        if (props.toolType == "7") {
            comChart.dispatchAction({
                type: "takeGlobalCursor",
                key: "brush",
                brushOption: {
                    brushType: "lineX", // 指定选框类型
                },
            });
        } else {
            comChart.dispatchAction({
                type: "none",
                key: "brush",
                removeOnClick: true,
                brushOption: {
                    brushType: "clear", // 指定选框类型
                },
            });
        }
        comChart.on("brushEnd", function (params) {
            if (params.areas.length != 0) {
                let start = params.areas[0].coordRange[0];
                let end = params.areas[0].coordRange[1];
                if (xdata.length > 0) {
                    let startTime = xdata[start];
                    let endTime = xdata[end];
                    emits("toolChange", {
                        type: "dateType",
                        data: [startTime, endTime],
                        brushValue: "7",
                    });
                }
            }
        });
    }
      // 拐点悬浮框
      function mouseleavesymbol(){
        state.symShow=false
    }
    watchEffect(() => {
        state.maxMinScale=props.maxMinScale
        if (props.toolType == '13') {
            let statesrc = comChart.getDataURL({
                type: "png", //jpeg | jpeg
                pixelRatio: 1,
                backgroundColor: "#fff", //背景色白色
            });
            printJS({
                printable: statesrc, //表格的数据
                type: "image",
                imageStyle: "width:100%;height:100%; margin-bottom:0px;",
            });
        }
        if (props.toolType == "-1") {
            state.youBoxShow = false;
        }
        if (props.toolType == '12') {
            var picInfo = comChart.getDataURL({
                type: 'png',
                pixelRatio: 1.5, //放大两倍下载，之后压缩到同等大小展示。解决生成图片在移动端模糊问题
                backgroundColor: '#000'
            }); //获取到的是一串base64信息
            const elink = document.createElement('a');
            elink.download = "历史曲线图";
            elink.style.display = 'none';
            elink.href = picInfo;
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink)
        }
        if (JSON.stringify(props.chartList) != "{}" || JSON.stringify(props.statusList) != "{}") {
            state.symbolShow = props.symbolShow
            state.splitNumber = props.splitNumber
            nextTick(() => {
                comChart = echarts.init(document.getElementById("comChart"));
                setC1(props.chartList, props.statusList)
            })
        } else {
            nextTick(() => {
                // comChart = echarts.init(document.getElementById("comChart"));
                // setC1({}, {})
            })
        }
    })
    onMounted(() => {
        window.addEventListener('resize', () => {
            if(comChart){
                comChart.resize()
            }
        })
    })
</script>